﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Collections;
using System.Security.Permissions;
namespace FsDump
{
    
    public partial class MainFrm : Form
    {
        private ListViewColumnSorter lvwColumnSorter;
        MyGpsDump Pcontrol;
        private delegate void adicionaItemNaListaHandler(ListViewItem strVal);
        public static int MyId;
        int P2size = 0;
        public const int WM_COPYDATA = 74;
        [StructLayout(LayoutKind.Sequential)]
        public struct CopyData
        {
            public IntPtr dwData;
            public int cbData;
            public IntPtr lpData;
        }
        [DllImport("User32", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
        static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
        public MainFrm()
        {
            MainClass.ReadConfig();
            ConfigFrm Config = new ConfigFrm();
            Config.ShowDialog();
            if (Config.DialogResult == DialogResult.OK)
            {
                if (MainClass.Interfaces != MainClass.InterfacesO)
                {
                    MainClass.InterfacesO = MainClass.Interfaces;
                    
                }
            }
            Config.Dispose();
            GetCn();
            InitializeComponent();
            AlignControls();
            CreateHeadersAndFillListView();
            lvwColumnSorter = new ListViewColumnSorter();
            this.lvPilots.ListViewItemSorter = lvwColumnSorter;
        }

        private void adicionaItemNaLista(ListViewItem strVal)
        {
            if (this.lvPilots.InvokeRequired)
                this.lvPilots.Invoke(new adicionaItemNaListaHandler(adicionaItemNaLista), new object[] { strVal });
            else
                this.lvPilots.Items.Add(strVal);
        }


        private void CreateHeadersAndFillListView()
        {
             ColumnHeader colHead;
           
               
                colHead = new ColumnHeader();
                colHead.Text = "ID";
                colHead.Width = 35;
                this.lvPilots.Columns.Add(colHead);
                colHead = new ColumnHeader();
                colHead.Text = "CIVLID";
                colHead.Width = 48;
                this.lvPilots.Columns.Add(colHead);

                colHead = new ColumnHeader();
                colHead.Text = "PILOT NAME";
                colHead.Width = 150;
                this.lvPilots.Columns.Add(colHead);
                colHead = new ColumnHeader();
                colHead.Text = "STATUS";
                colHead.Width = 100;
           
            this.lvPilots.Columns.Add(colHead);
        }
         internal void PaintListView(string root)
        {
            try
            {
               
                ListViewItem lvi;
                ListViewItem.ListViewSubItem lvsi;
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(root);
                DirectoryInfo[] dirs = dir.GetDirectories();
                FileInfo[] files = dir.GetFiles("*.kml");

                this.lvPilots.Items.Clear();

                this.lvPilots.BeginUpdate();

                foreach (System.IO.FileInfo fi in files)
                {
                    string[] o = fi.Name.Split('.');
                    lvi = new ListViewItem();                    
                    lvi.Text = o[o.Length-2];
                    lvi.ImageIndex = 1;
                    lvi.Tag = fi.FullName.Replace(".kml",".igc");
                    lvsi = new ListViewItem.ListViewSubItem();
                    string[] u = MainClass.SearchForCOMPIDonDB(lvi.Text);
                    lvsi.Text = u[1];
           
                    lvi.SubItems.Add(lvsi);
                    lvsi = new ListViewItem.ListViewSubItem();
                    lvsi.Text = u[2];
                    lvi.SubItems.Add(lvsi);
                    
                    lvsi = new ListViewItem.ListViewSubItem();
                   // lvsi.Text = fi.CreationTime.ToString("yyyyMMddHHmmss");
                    lvsi.Text = fi.LastWriteTime.ToString("yyyyMMddHHmmss");
                    lvi.SubItems.Add(lvsi);

                    this.lvPilots.Items.Add(lvi);
                }
                this.lvPilots.EndUpdate();
            }
            catch (System.Exception err)
            {
                MessageBox.Show("Error: " + err.Message);
            }
            this.lvPilots.View = View.Details;
            foreach (ColumnHeader ch in this.lvPilots.Columns)
            {
                ch.Width = -2;
            }
        }

        private void lvPilots_ItemActivate(object sender, System.EventArgs e)
        {
            System.Windows.Forms.ListView lw = (System.Windows.Forms.ListView)sender;
            try
            {
                string filename = lw.SelectedItems[0].Tag.ToString();

                try
                {
                    System.Diagnostics.Process.Start(filename);
                }
                catch
                {
                    return;
                }
            }
            catch {
                return;
            }
        }
        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            if (m.Msg == WM_COPYDATA)
            {
                CopyData data;
                data = (CopyData)m.GetLParam(typeof(CopyData));
                string mess = Marshal.PtrToStringAnsi(data.lpData, data.cbData);
                InformPcontrol(data.dwData.ToString(), mess);
                m.Result = new IntPtr(1);
            }
            else
            {
                base.WndProc(ref m);
            }
        }
        public void GetCn()
        {
            StringBuilder ClassName = new StringBuilder(100);
            GetClassName(this.Handle, ClassName, ClassName.Capacity); ;
            MainClass.ClassName = ClassName.ToString();
            this.Text = MainClass.ClassName;
        }
        private void InformPcontrol(string wichPcontrol, string Msg)
        {
            for (int i = 0; i <= MainClass.Interfaces - 1; i++)
            {
                Control Ctrl = this.splitContainer1.Panel2.Controls[i];
                if (Ctrl.Name == wichPcontrol)
                {
                    Ctrl.Controls["TXT_STATUS"].Text = Msg;
                }
            }
        }
        private void MainFrm_Load(object sender, EventArgs e)
        {
 
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainClass.SaveConfig();
            bool downloading = false;
            foreach (Control c in this.splitContainer1.Panel2.Controls) {
                if (c.Controls["BT_S"].Enabled == false) {
                    downloading = true;
                    break;
                }
            }
            if (!downloading)
            {                
                Application.Exit();
            }
            else {
                MessageBox.Show("CANT GET OUT, WAIT FOR FINISH");
            }
        }
        
        private void AlignControls()
        {
            if (MainClass.Mode == 0)
            {
                PaintListView(MainClass.FlightsPath);
            }
            this.ClientSize = new System.Drawing.Size(705, 300);
            
            int Height = 0;            
            this.splitContainer1.Panel2.Controls.Clear();
            for (int i = 0; i <= MainClass.Interfaces - 1; i++)
            {
                MyId = i;
                Pcontrol = new MyGpsDump();
                Pcontrol.Name = i.ToString();
                Pcontrol.Dock = DockStyle.Top;
                Height = Height + Pcontrol.Height;
                this.splitContainer1.Panel2.Controls.Add(Pcontrol);
                Pcontrol.Location = new Point(0, i * Pcontrol.Height);
                this.ClientSize = new Size(this.ClientSize.Width, this.ClientSize.Height + Pcontrol.Height);
                this.splitContainer1.SplitterDistance = this.splitContainer1.Height - 4 - Pcontrol.Height * (i + 1);
                this.splitContainer1.Panel2MinSize = Pcontrol.Height * (i + 1);
                this.splitContainer1.Panel1MinSize = this.splitContainer1.Size.Height - this.splitContainer1.Panel2MinSize-4;
                P2size = this.splitContainer1.Panel2MinSize;
                Pcontrol.ButtonClick += new MyGpsDump.ButtonClickEventHandler(testControl1_ButtonClick);
                Pcontrol.Controls["BT_S"].BackColor = Color.Yellow;
            }
        }
        void testControl1_ButtonClick(object sender, EventArgs e)
        {
            PaintListView(MainClass.FlightsPath);
        }

        private void configureToolStripMenuItem_Click(object sender, EventArgs e)
        {


            bool downloading = false;
            foreach (Control c in this.splitContainer1.Panel2.Controls)
            {
                if (c.Controls["BT_S"].Enabled == false)
                {
                    downloading = true;
                    break;
                }
            }
            if (!downloading)
            {

                ConfigFrm Config = new ConfigFrm();
                Config.ShowDialog();
                if (Config.DialogResult == DialogResult.OK)
                {
                    if (MainClass.Interfaces != MainClass.InterfacesO)
                    {
                        MainClass.InterfacesO = MainClass.Interfaces;
                        AlignControls();
                    }
                }
                Config.Dispose();
            }
            else
            {
                MessageBox.Show("CANT GO IN CONFIG MODE, WAIT FOR GPSDUMP FINISH");

            }


        }

        private void saveInterfacesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainClass.SaveConfig();
        }

        private void lvPilots_ColumnClicked(object sender, ColumnClickEventArgs e) {
            // Determine if clicked column is already the column that is being sorted.
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                // Reverse the current sort direction for this column.
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            this.lvPilots.Sort();
        }

        private void lvPilots_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void deleteFlightToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (File.Exists(this.lvPilots.SelectedItems[0].Tag.ToString()))
            {
               File.Delete(this.lvPilots.SelectedItems[0].Tag.ToString());
            }
            if (File.Exists(this.lvPilots.SelectedItems[0].Tag.ToString().Replace("igc","kml")))
            {
                File.Delete(this.lvPilots.SelectedItems[0].Tag.ToString().Replace("igc","kml"));
            }
            PaintListView(MainClass.FlightsPath);
        }

        private void editFlightToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            string filename = this.lvPilots.SelectedItems[0].Tag.ToString();
            string gpsarg =  filename;
            System.Diagnostics.Process.Start(MainClass.GpsDumpPath, " /logfile=" + "\"" + filename.Replace("igc", "kml") + "\"");            
        }     
    }
}
